import { isEmpty } from 'lodash-es'

// 接口请求数据处理, null和undefined去掉
export const requestParamsFormat = (formData: any) => {
  if (isEmpty(formData)) {
    return formData
  }
  if (typeof formData === 'object' && !Array.isArray(formData)) {
    Object.keys(formData).forEach((item) => {
      if (
        isEmpty(formData[item]) &&
        typeof formData[item] !== 'number' &&
        typeof formData[item] !== 'boolean'
      ) {
        // isEmpty(number) === true
        delete formData[item]
      } else if (typeof formData[item] === 'object') {
        requestParamsFormat(formData[item])
      }
    })
  } else if (Array.isArray(formData)) {
    formData.forEach((el) => {
      if (!isEmpty(el) && typeof el === 'object') {
        requestParamsFormat(el)
      }
    })
  }
  return formData
}

type TransformTreeParams<T = any> = {
  list: any[]
  parentId: string | number // 父级id
  parentKey: keyof T // 父级id键名
  key?: keyof T | 'id' // 子级id键名
  children?: string // 子级列表名
  handleItem?: (item: any) => any
}

export const getTreeByList = <T>(params: TransformTreeParams<T>) => {
  const {
    list,
    parentId,
    parentKey,
    key = 'id',
    handleItem,
    children = 'children'
  } = params
  const tree = list.filter((item) => item[parentKey] === parentId)
  return tree.map((item) => {
    item[children] = getTreeByList({
      list,
      parentId: item[key],
      key,
      parentKey,
      children,
      handleItem
    })
    return handleItem ? handleItem(item) : item
  })
}
